// hash
let _Vue;
export default class VueRouter {
  constructor(opts) {
    // 路由组件映射
    this.routeMap = {};
    // 路由
    this.routes = opts.routes;
    // 当前路由
    this.data = _Vue.observable({
      current: "#/",
    });
    this.init();
  }

  static install(Vue) {
    if (VueRouter.install.installed) {
      return;
    }
    VueRouter.install.installed = true;
    _Vue = Vue;
  }
  init() {
    this.initRouteMap();
    this.initComponent();
    this.initEvent();
  }
  initRouteMap() {
    let path;
    this.routes.forEach((route) => {
      path = this.getHashPath(route.path);
      this.routeMap[path] = route.component;
    });
  }
  initComponent() {
    const that = this;
    _Vue.component("router-link", {
      props: {
        to: String,
      },
      methods: {
        handleClick(e) {
          e.preventDefault();
          const path = that.getHashPath(this.to);
          location.hash = path;
          that.data.current = path;
        },
      },
      render(h) {
        return h(
          "a",
          {
            href: this.to,
            on: {
              click: this.handleClick,
            },
          },
          [this.$slots.default]
        );
      },
    });

    _Vue.component("router-view", {
      render(h) {
        const component = that.routeMap[that.data.current];
        return h(component);
      },
    });
  }
  initEvent() {
    window.addEventListener("hashchange", (e) => {
      console.log(location.hash);
      this.data.current = location.hash;
    });
  }
  getHashPath(path) {
    return "#" + path;
  }
}
